import React, { Component } from 'react'
import { Table, Button, Checkbox, message, Spin, Alert } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { inject, observer } from 'mobx-react/index'
import qs from 'qs'

import getData from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'

import './index.less'

const { leagueManagement: { validateInvite, getAllOrg, applyJoinLeague, getOrgDatas, joinLeague }} = address

@inject('BreadCrumb')
@observer
class InvitePage extends Component {
  constructor(props) {
    super(props)
    const { location: { pathname }, match: { params: { id, name }}} = props
    const pageName = pathname.includes('apply') ? 'apply' : pathname.includes('invite') ? 'invite' : ''
    let params = {
      _org: name,
      consortiumId: id,
    }
    if (pageName === 'invite') {
      // 邀请组织
      const query = this.formatSearch()
      params = {
        _user: query.user,
        _org: query._org,
        consortiumId: query._id,
      }
    }
    if (pageName === 'apply') {
      // 申请加入组织
      const url_apply = '/dashboard/fabric/leagueInfo/' + id + '/' + name // id
      props.BreadCrumb.setSearch(name)
      props.BreadCrumb.setUrl(url_apply)
    }

    this.state = {
      _user: params._user || '', // 用户信息
      _org: params._org || '', // 组织名称
      consortiumId: params.consortiumId || '', // 申请的联盟id
      data: null,
      selectedRowKeys: [],
      loading: false,
      inviteLinkLoading: false,
      pageName,
      leagueInfo: {},
      organizationType: [
        { id: 'peer', text: 'peer', checked: false },
        { id: 'orderer', text: 'orderer', checked: false },
      ],
    }
  }

  componentDidMount() {
    const { pageName } = this.state
    if (pageName === 'apply') {
      // 获取未加入联盟的组织
      this.getFreeData()
    } else if (pageName === 'invite') {
      this.validateLink()
      this.getLeagueInfo() // 获取联盟信息
    }
  }

  async getLeagueInfo() {
    const { consortiumId } = this.state
    const { status, data } = await getData().get(address.leagueManagement.leagueInfo.format({ consortiumId }))
    if (status === 200) {
      this.setState({
        leagueInfo: data || {},
      })
    }
  }

  // 获取该用户下所有组织
  getAllData = () => {
    this.setState({
      loading: true,
    })
    getData().get(getAllOrg).then(res => {
      switch (res.status) {
      case 200:
        this.setState({
          data: res.data,
        }, () => {
          this.setState({
            loading: false,
          })
        })
        this.totalData = res.data
        break
      default:
        message.error('组织获取失败')
        break
      }
    })
  }

  // 获取未加入联盟的组织
  getFreeData = async() => {
    this.setState({
      loading: true,
    })
    const { consortiumId } = this.state
    let { status, data } = await getData().get(getOrgDatas.format({ id: consortiumId }))
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.totalData = data
      this.setState({
        data,
      })
    }
  }

  // 验证分享链接
  validateLink = () => {
    this.setState({
      inviteLinkLoading: true,
    })
    const obj = this.formatSearch()
    getData().get(validateInvite.format({ eventId: obj.eventId })).then(res => {
      this.setState({
        inviteLinkLoading: false,
      })
      switch (res.status) {
      case 200:
        // 获取未加入联盟的组织
        this.getFreeData()
        break
      case 408:
        message.error('邀请链接失效， 2s后跳转至概览页').then(() => {
          this.props.history.push({
            pathname: `/dashboard/fabric`,
          })
        })
        break
      case 410:
        message.error('正在审核中或已经加该联盟，2s后跳转至概览页').then(() => {
          this.props.history.push({
            pathname: `/dashboard/fabric`,
          })
        })
        break
      default:
        message.error(res.data.message + '，2s后跳转至概览页').then(() => {
          this.props.history.push({
            pathname: `/dashboard/fabric`,
          })
        })
        break
      }
    })
  }

  // 获取地址栏参数
  formatSearch = () => {
    const { location: { search = '' }} = this.props
    return qs.parse(search.slice(1))
  }

  componentWillUnmount() {
    this.props.BreadCrumb.setSearch('')
    this.props.BreadCrumb.setUrl('')
  }

  dropDownRender = (setSelectedKeys, clearFilters, confirm) => {
    const { organizationType } = this.state
    return (
      <div>
        <div className="ant-dropdown-menu">
          {
            organizationType.map((item, idx) => {
              return (
                <li className="ant-dropdown-menu-item" key={item.text}
                  style={{ background: item.checked ? '#E9F5FF' : '#fff' }}
                  onClick={() => this.setcheckFn(item, idx, 'organizationType', setSelectedKeys)}
                >
                  <Checkbox checked={item.checked}> <span style={{ color: '#171E2D' }}>{item.text}</span></Checkbox>
                </li>
              )
            })
          }
        </div>
        <div className="ant-table-filter-dropdown-btns">
          <span className="clear"
            onClick={() => this.clear(clearFilters, 'organizationType')}
          >
            重置</span>
          <span className="confirm"
            onClick={() => this.confirm(confirm)}
          >确定</span>

        </div>

      </div>
    )
  }

  setcheckFn = (level, index, flag, setSelectedKeys) => {
    // level 当前点击的check项数据
    let data = this.state[flag]
    data[index].checked = !level.checked
    this.setState({
      [flag]: data,
    })
    setSelectedKeys(data.filter(item => { return item.checked === true }))
  }

  confirm = (confirm) => {
    confirm && confirm()
  }

  // 重置 重置为初始状态
  clear = (clear, flag) => {
    let data = this.state[flag]
    data.forEach(element => {
      element.checked = false
    })
    this.setState({
      [flag]: data,
    })
    clear()
  }

  changeTableFn = () => {
    let { organizationType } = this.state
    let _list = [] // 筛选后数据
    let filterList = organizationType.filter(item => item.checked)
    if (filterList && filterList.length) {
      filterList = filterList.map(ele => ele.id)
    } else {
      this.setState({
        data: this.totalData,
      })
    }
    if (filterList.length) {
      this.totalData.forEach(item => {
        filterList.includes(item.type) && _list.push(item)
      })
      this.setState({
        data: _list,
      })
    }
  }

  goBack = () => {
    const { pageName } = this.state
    if (pageName === 'invite') {
      this.props.history.push('/dashboard')
    } else {
      this.props.history.go(-1)
    }
  }

  joinOrg = () => {
    const { pageName, selectedRowKeys } = this.state
    if (pageName === 'invite') {
      const obj = this.formatSearch()
      const option = {
        orgIds: selectedRowKeys,
      }
      getData().post(joinLeague.format({ eventId: obj.eventId }), option).then(res => {
        switch (res.status) {
        case 200:
          message.info('当前联盟创建者正在审核中，2s后跳转至概览页').then(() => {
            this.props.history.push({
              pathname: `/dashboard/fabric`,
            })
          })

          break
        default:
          message.error(res.data.message + '，2s后跳转至概览页').then(() => {
            this.props.history.push({
              pathname: `/dashboard/fabric`,
            })
            // this.props.history.push({
            //   pathname: `/dashboard/fabric/leagueInfo/${obj._id}/${obj._org}`
            // })
          })
          break
        }
      })
    } else if (pageName === 'apply') {
      const { consortiumId } = this.state
      const options = {
        orgIds: selectedRowKeys,
        consortiumId,
      }
      getData().post(applyJoinLeague, options).then(res => {
        switch (res.status) {
        case 200:
          message.success('申请成功，等待投票')
          this.props.history.go(-1)
          break
        case 409:
          message.error('当前用户还未加入该联盟')
          break
        default:
          message.error('加入联盟失败')
          break
        }
      })
    }
  }

  createOrg = () => {
    this.props.history.push('/dashboard/fabric/createOrganization')
  }

  render() {
    const { _user, _org, data, pageName, loading, inviteLinkLoading, leagueInfo } = this.state
    const columns = [
      {
        title: '我的组织',
        dataIndex: 'display_name',
      },
      {
        title: '组织类型',
        dataIndex: 'type',
        width: 132,
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
          return this.dropDownRender(setSelectedKeys, clearFilters, confirm)
        },
      },
      {
        title: '节点数量',
        dataIndex: 'nodesNum',
      },
    ]
    const rowSelection = {
      onChange: (selectedRowKeys) => {
        this.setState({
          selectedRowKeys,
        })
      },
    }

    return (
      inviteLinkLoading ? <Spin style={{ height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }} size="large" />
        : <div className="invite-page common">
          {
            pageName === 'invite'
              ? <h1 className="invite-title">移动云用户{_user}邀请您加入联盟“{decodeURI(_org)}”，请选择组织加入联盟</h1>
              : <h1 className="invite-title">请选择需要申请加入联盟“{decodeURI(_org)}”的组织</h1>
          }
          {
            pageName === 'invite' && (
              <Alert style={{ width: '664px', marginTop: '10px' }} showIcon message={
                leagueInfo.isGuomi ? '您当前的联盟是国密联盟 不能添加非国密组织' : '您当前的联盟是非国密联盟 不能添加国密组织'
              } type="warning" />
            )
          }
          <div className="orgList-box">
            <Spin spinning={loading}>
              {
                data && data.length
                  ? <div className="invite-box">
                    <Table
                      rowSelection={{
                        ...rowSelection,
                      }}
                      rowKey={record => record.id}
                      getPopupContainer={node => {
                        if (node) {
                          return node.parentNode
                        }
                        return document.body
                      }}
                      onChange={this.changeTableFn}
                      columns={columns}
                      dataSource={data}
                      pagination={false}

                    />
                    <Button type="primary" className="mt24" onClick={this.createOrg}><PlusOutlined />创建组织</Button>
                  </div>
                  : <div className="invite-box empty">
                    <img width={112} src={require('@/images/fabric/1.svg')} alt="" />
                    <div className="empty-go">
                      <span>还没有任何组织？</span>
                      <span style={{ cursor: 'pointer' }} onClick={this.createOrg}>去创建</span>
                    </div>
                  </div>
              }
            </Spin>
          </div>

          <div className="invite-btn">
            <Button type="primary" disabled={!this.state.selectedRowKeys.length} onClick={this.joinOrg}>加入</Button>
            {
              pageName === 'invite'
                ? <Button style={{ marginLeft: '8px' }} type="primary" danger onClick={this.goBack}>拒绝</Button>
                : <Button style={{ marginLeft: '8px' }} onClick={this.goBack}>取消</Button>
            }
          </div>
        </div>
    )
  }
}

export default InvitePage
